package com.sojson.config.init;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.sojson.dao.SentinelDao;
import com.sojson.entity.po.Sentinel;
import com.sojson.util.cache.redis.impl.RedisUtilImpl;

import lombok.extern.slf4j.Slf4j;

/**
 * 应用程序初始化类
 * 
 * @author liu
 * @date 2020-11-02
 */
@Slf4j
@Component
public class WebInit implements CommandLineRunner {

    public static final RedisUtilImpl CACHE;
    @Resource
    private SentinelDao sentinelDaoImpl;

    static {
        CACHE = RedisUtilImpl.getInstances();
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("开始执行应用程序自定义动态初始化操作！");
        initSentinel();
        log.info("应用程序自定义动态初始化操作执行完毕！");
    }

    /**
     * 设置Sentinel流控
     */
    private void initSentinel() throws Exception {
        // 开始设置字典
        log.info("开始设置Sentinel流控！");

        // 查询所有属性
        List<Sentinel> listAll = sentinelDaoImpl.listAll();
        for (Sentinel sentinel : listAll) {
            CACHE.setStr(sentinel.getKey(), sentinel.getContent());
        }

        log.info("Sentinel流控已加载到缓存！");
    }

}